import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui';
const URL = "http://10.237.55.112:8080"
const service = axios.create({
    baseURL: URL, // url = base url + request url
    timeout: 10000,// request timeout
    withCredentials: true
})

// http request 拦截器
service.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');
        config.headers['token'] = token;
        return config;
    },
    error => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        // 访问响应头
        const headers = response.headers;
        // 检查是否存在 token 字段
        if (headers['token']) {
            // 将 token 保存到 localStorage
            localStorage.setItem('token', headers['token']);
        }
        if (response.data.code == 401 || response.data.code == 402) {
            Message.warning("登录信息已过期,请重新登录！");
            // 判断当前页面是否为首页
            if (router.currentRoute.path != '/home') {
                router.replace({ path: '/home', query: { status: 'login' } });
            }
        }
        return response.data;
    },
    error => {
        return Promise.reject(error);
    }
);

export default service
